﻿using System;
using UnityEngine;
using UnityEngine.UI;

public class CELog : MonoBehaviour
{
    private static CELog mInstance;

    public static void Warring(string _msg)
    {
        Log(_msg, "yellow");
    }

    public static void Error(string _msg)
    {
        Log(_msg, "red");
    }

    public static void Log(string _msg)
    {
        mInstance.SetLog(_msg);
    }

    public static void Log(string _msg, string _color)
    {
        mInstance.SetLog("<color=" + _color + ">" + _msg + "</color>");
    }

    public Text logPanel;
    public int maxLogNum = 100;

    private string mLogMsg;
    private int mCurrentLogNum;


    private void Start()
    {
        Application.logMessageReceived += HandleLog;
        mInstance = this;
        SetLog("CELog init complete");
    }

    private void Update()
    {
        logPanel.text = mLogMsg;
    }

    private static void HandleLog(string _logString, string _stackTrace, LogType _type)
    {
        switch (_type)
        {
            case LogType.Error:
                Error(_logString);
                Error(_stackTrace);
                break;
            case LogType.Assert:
                Log(_logString);
                break;
            case LogType.Warning:
                Warring(_logString);
                break;
            case LogType.Log:
                Log(_logString);
                break;
            case LogType.Exception:
                Error(_logString);
                Error(_stackTrace);
                break;
            default:
                throw new ArgumentOutOfRangeException("_type", _type, null);
        }
    }


    private void SetLog(string _msg)
    {
        mCurrentLogNum++;
        if (mCurrentLogNum >= maxLogNum)
        {
            mLogMsg = "";
        }

        mLogMsg += _msg + "\n";
    }
}